package cc.linker.steplink.crm.merchant.service;

import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.merchant.dao.ContentMapper;
import cc.linker.steplink.crm.merchant.dao.ShopGoodsMapper;
import cc.linker.steplink.crm.merchant.pojo.ContentPo;
import cc.linker.steplink.crm.merchant.pojo.ShopGoods;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cc.linker.steplink.crm.merchanth5.service.ZsContentService.CONTENT_SCHEDULE;

@Slf4j
@Service
public class ContentService {

    @Autowired
    private ContentMapper contentMapper;

    @Autowired
    private NewMallService newMallService;

    @Autowired
    private ShopGoodsService shopGoodsService;

    @Autowired
    private ShopGoodsMapper shopGoodsMapper;

    @Autowired
    private ShopGoodsColumnService shopGoodsColumnService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private HttpService httpService;

    @Value("${system.scrm.materialCenter}")
    private String materialCenterUrl;

    public void save(Map<String, Object> params) {
        Integer contentId = (Integer) params.get("contentId");
        Integer columnId = (Integer) params.get("columnId");
        List goodsGroup = (List) params.get("contentGroup");
        String goodsName = (String) params.get("contentTitle");
        String goodsCover = (String) params.get("contentCover");
        String goodsContent = (String) params.get("contentIntroduce");
        params.putIfAbsent("moneyAmount", 0);
        params.putIfAbsent("originalCost", 0);
        params.put("goodsGroup", goodsGroup);
        params.put("goodsName", goodsName);
        params.put("goodsCover", goodsCover);
        params.put("goodsContent", goodsContent);
        params.put("purchaseType", 2);
        params.put("goodsType", 3);
        // 先存商品
        newMallService.savePublic(params);
        // 再存内容
        if (contentId != null) {
            // contentComplete schedule 播放进度清除
            Map<String, Object> oldContent = contentMapper.getContentCompleteByContentId(contentId);
            Integer contentType = (Integer) oldContent.get("contentType");
            if (contentType != null && contentType == 2) {
                String contentComplete = (String) oldContent.get("contentComplete");
                if (contentComplete != null && !contentComplete.equals(params.get("contentComplete"))) {
                    redisTemplate.delete(CONTENT_SCHEDULE + contentId);
                }
            }
            Integer oldPurchase = (Integer) oldContent.get("purchase");
            Object newPurchaseObj = params.get("purchase");
            if (oldPurchase != null && newPurchaseObj != null) {
                Integer newPurchase = Integer.valueOf(newPurchaseObj.toString());
                // 本来单独售卖，然后不单独售卖了，取消推广状态
                boolean b = oldPurchase == 1 || oldPurchase == 3;
                boolean b1 = newPurchase == 2;
                if (b && b1) {
                    ContentPo contentPo = contentMapper.contentInfo(params);
                    Long goodsId = contentPo.getGoodsId();
                    shopGoodsColumnService.notJoining(goodsId.toString());
                }
                if (newPurchase == 1 || newPurchase == 3) {
                    params.put("isFree", 0);
                }
            }
            // 编辑
            contentMapper.update(params);
            // 旧专栏id
            Integer oldColumnId = contentMapper.getColumnIdByContentId(params);
            // 删除关系
            if (oldColumnId != null && !oldColumnId.equals(columnId)) {
                // 本来关联了专栏且准备关联另一个和之前不一样的专栏或取消关联
                this.deleteContentColumnRelated(contentId);
            }
            // 增加关联关系
            if (columnId != null && !columnId.equals(oldColumnId)) {
                // 之前没关联专栏或者新旧专栏不一样
                Integer maxSerialNum = contentMapper.getMaxSerialNumByColumnId(params);
                params.put("serialNum", maxSerialNum + 1);
                contentMapper.insertContentColumn(params);
            }
            if (columnId != null) {
                // 若为免费专栏，则把内容移除
                // 小B内容是设置了返润，又被添加到大麦商城，此时把这个内容关联到免费的专栏，那么大麦商城要自动删除此内容。
                Map<String, Object> shopGoodsColumnDetail = shopGoodsColumnService.getShopGoodsColumnDetail(columnId, "");
                Integer isFree = (Integer) shopGoodsColumnDetail.get("isFree");
                if (isFree == 1) {
                    ContentPo contentPo = contentMapper.contentInfo(params);
                    Long goodsId = contentPo.getGoodsId();
                    shopGoodsColumnService.notJoining(goodsId.toString());
                }
            }
        } else {
            // 新增
            contentMapper.insert(params);
            if (columnId != null) {
                // 增加关联关系
                Integer maxSerialNum = contentMapper.getMaxSerialNumByColumnId(params);
                params.put("serialNum", maxSerialNum + 1);
                contentMapper.insertContentColumn(params);
            }
        }
    }

    /**
     * @param contentId
     * @param orgId
     * @param customerId
     */
    public void copy(String contentId, String orgId, String customerId) {
        Map<String, Object> contentInfo = contentMapper.getContentInfoByContentId(contentId);
        // 根据 商品id查询分组
        List<Long> contentGroup = contentMapper.getGroupByGoodsId((Long) contentInfo.get("goodsId"));
        Map<String, Object> params = new HashMap<>();
        params.put("contentTitle", contentInfo.get("contentTitle"));
        params.put("contentCover", contentInfo.get("contentCover"));
        params.put("contentIntroduce", contentInfo.get("contentIntroduce"));
        params.put("contentGroup", contentGroup);//
        params.put("contentInfo", contentInfo.get("contentInfo"));
        params.put("contentComplete", contentInfo.get("contentComplete"));
        params.put("contentAudition", contentInfo.get("contentAudition"));
        params.put("contentType", contentInfo.get("contentType"));
        params.put("purchase", contentInfo.get("purchase"));
        params.put("resourceId", contentInfo.get("resourceId"));
        params.put("audResourceId", contentInfo.get("audResourceId"));
        params.put("videoType", contentInfo.get("videoType"));
        Integer columnId = StringUtils.isEmpty(contentInfo.get("columnId")) ? null : Integer.parseInt(contentInfo.get("columnId").toString());
        params.put("columnId", columnId);
        Double moneyAmount = Double.parseDouble(contentInfo.get("moneyAmount").toString()) / 100;
        params.put("moneyAmount", moneyAmount);
        params.put("goodsStatus", contentInfo.get("goodsStatus"));
        params.put("originalCost", contentInfo.get("originalCost"));
        params.put("shareInfo", contentInfo.get("shareInfo"));
        params.put("shareTitle", contentInfo.get("shareTitle"));

        params.put("orgId", orgId);
        params.put("customerId", customerId);
        save(params);
    }


    /**
     * 删除内容关联
     *
     * @param contentId 内容Id
     */
    public void deleteContentColumnRelated(Integer contentId) {
        Map<String, Object> params = new HashMap<>();
        params.put("contentId", contentId);
        // 专栏id
        Integer columnId = contentMapper.getColumnIdByContentId(params);
        if (columnId == null) {
            return;
        }
        params.put("columnId", columnId);
        // 序号
        Integer serialNum = contentMapper.getSerialNumByColumnIdAndContentId(params);
        contentMapper.deleteContentColumn(params);
        params.put("flag", 0);
        params.put("from", serialNum);
        contentMapper.updateSerialNumByColumnIdAndContentId(params);
    }

    public Object getContentList(Map<String, Object> params) {
        int pageIndex = 1, pageSize = 20;
        Object pi = params.get("pageIndex");
        if (pi instanceof Integer && (int) pi >= 0) {
            pageIndex = (int) pi;
        }
        Object ps = params.get("pageSize");
        if (ps instanceof Integer && (int) ps >= 0) {
            pageSize = (int) ps;
        }
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> contentList = contentMapper.getContentList(params);
        return new PageInfo<>(contentList);
    }

    /**
     * @param goodsId     关联商品id
     * @param goodsStatus 商品状态 0 待上架 1 已上架 2 已下架
     * @param isDelete    是否删除 0 未删除 1 已删除
     * @Description: 内容上下架或删除
     * @Return: void
     * @Author:ch
     * @Date: 2019/11/22 9:53
     * @Version:
     **/
    public void updateStatus(Map<String, Object> params, String adminId, String orgId, Boolean ifSales) {
        Long goodsId = Long.valueOf(params.get("goodsId").toString());
        Long[] goodsIds = {goodsId};
        Map map = new HashMap();
        map.put("goodsId", goodsId);
        map.put("orgId", orgId);
        Integer mine = 0;
        ShopGoods shopGoods = shopGoodsService.getGoods(goodsId);
        String belongId = shopGoods.getBelongId();
        if (belongId != null && !belongId.equals("") && !ifSales) {
            mine = 1;
        }
        if (params.get("goodsStatus") != null) {
            if (!ifSales) {
                newMallService.changeGoodStatus(map, mine);
            } else {
                map.put("mine", mine);
                map.put("adminId", adminId);
                newMallService.updateStatus(map);
            }

        }
    }

    public void delete(Map<String, Object> params, String adminId, String orgId, Boolean ifSales) {
        Long goodsId = Long.valueOf(params.get("goodsId").toString());
        Long[] goodsIds = {goodsId};
        Map map = new HashMap();
        map.put("goodsId", goodsId);
        map.put("orgId", orgId);
        Integer mine = 0;
        ShopGoods shopGoods = shopGoodsService.getGoods(goodsId);
        String belongId = shopGoods.getBelongId();
        if (belongId != null && !belongId.equals("") && !ifSales) {
            mine = 1;
        }
        shopGoodsService.delete(goodsIds, adminId, orgId, mine, ifSales);
        if (mine == 0) {
            //删除内容
            contentMapper.delete(params);
//            contentMapper.deleteContentColumn(params);
            Integer contentId = (Integer) params.get("contentId");
            this.deleteContentColumnRelated(contentId);
        }
    }

    public Object contentList(Map<String, Object> params) {
        int pageIndex = 1, pageSize = 20;
        Object pi = params.get("pageIndex");
        if (pi instanceof Integer && (int) pi >= 0) {
            pageIndex = (int) pi;
        }
        Object ps = params.get("pageSize");
        if (ps instanceof Integer && (int) ps >= 0) {
            pageSize = (int) ps;
        }
        PageHelper.startPage(pageIndex, pageSize);
        List<ContentPo> contentList = contentMapper.contentList(params);
        return new PageInfo<>(contentList);
    }

    public ContentPo contentInfo(Map<String, Object> params) {
        return contentMapper.contentInfo(params);
    }

    public Integer getResCount(String resId) {
        return contentMapper.getResCount(resId);
    }

    public void setFree(Map<String, Object> params) {
        // 当内容从收费转为免费（被设置为免费浏览、关联免费专栏），若此内容参与返润，则将此商品转为“不参与”
        ContentPo contentPo = contentMapper.contentInfo(params);
        if (contentPo == null) {
            throw GlobalException.build("商品不存在或已删除");
        }
        Integer isFree = contentPo.getIsFree();
        Long goodsId = contentPo.getGoodsId();
        if (isFree == 0) {
            shopGoodsColumnService.notJoining(goodsId.toString());
        }
        contentMapper.setFree(params);
        redisTemplate.delete("goodsInfo:goods_info_" + goodsId);
    }

    public void setSerialNum(Map<String, Object> params) {
        Integer oldSerialNum = contentMapper.getSerialNumByColumnIdAndContentId(params);
        if (oldSerialNum == null) {
            throw GlobalException.build("参数不正确");
        }
        Object serialNumObj = params.get("serialNum");
        if (serialNumObj == null) {
            throw GlobalException.build("参数不正确");
        }
        Integer serialNum = Integer.valueOf(serialNumObj.toString());
        if (oldSerialNum.equals(serialNum)) {
            throw GlobalException.build("排序相同");
        }
        Integer maxSerialNum = contentMapper.getMaxSerialNumByColumnId(params);
        if (serialNum < 1) {
            throw GlobalException.build("序号最小为1");
        }
        if (serialNum > maxSerialNum) {
            throw GlobalException.build("序号输入过大,该专栏最大序号：[" + maxSerialNum + "]");
        }
        if (oldSerialNum < serialNum) {
            params.put("flag", 0);
            params.put("from", oldSerialNum + 1);
            params.put("to", serialNum);
        } else {
            params.put("flag", 1);
            params.put("from", serialNum);
            params.put("to", oldSerialNum - 1);
        }
        contentMapper.updateSerialNumByColumnIdAndContentId(params);
        contentMapper.setSerialNumByColumnIdAndContentId(params);

    }

    public Long getGoodsIdByContentId(String contentId) {
        return contentMapper.getGoodsIdByContentId(contentId);
    }

    public Map<String, Object> getMaterialList(Map<String, Object> param) throws IOException, URISyntaxException {
        Map<String, String> postParam = new HashMap<>();
        postParam.put("Content-Type", "application/json;charset=UTF-8");
        String resStr = httpService.doPost(materialCenterUrl + "/api/MaterialAPI/List", JSON.toJSONString(param), postParam);
        Map resMap = (Map) JSON.parse(resStr);
        if (null != resMap) {
            if ("200".equals(resMap.get("Code").toString())) {
                List<Map<String, Object>> list = (List) resMap.get("List");
                if (list.size() > 0) {
                    for (Map<String, Object> li : list) {
                        if ("3".equals(li.get("Type").toString())) {
                            Map materialDetail = getMaterialDetail(li.get("ResId").toString());
                            Map previewObj = (Map) materialDetail.get("PreviewObj");
                            li.put("newsUrl", previewObj.get("Url"));
                        } else {
                            li.put("newsUrl", "");
                        }
                    }
                }
                Map<String, Object> res = new HashMap<>();
                res.put("list", list);
                res.put("count", resMap.get("Count"));
                return res;
            } else {
                throw GlobalException.build(resMap.get("ErrMsg").toString());
            }
        }
        throw GlobalException.build("系统繁忙，请稍后再试（ERR:MaterialList）");
    }

    public Map getMaterialDetail(String ResId) throws IOException, URISyntaxException {
        Map<String, Object> param = new HashMap<>();
        param.put("ResId", ResId);
        Map<String, String> postParam = new HashMap<>();
        postParam.put("Content-Type", "application/json;charset=UTF-8");
        String resStr = httpService.doPost(materialCenterUrl + "/api/MaterialAPI/ResDetail", JSON.toJSONString(param), postParam);
        Map resMap = (Map) JSON.parse(resStr);
        if (null != resMap) {
            if ("200".equals(resMap.get("Code").toString())) {
                resMap.remove("Code");
                resMap.remove("ErrMsg");
                return resMap;
            } else {
                throw GlobalException.build(resMap.get("ErrMsg").toString());
            }
        }
        throw GlobalException.build("系统繁忙，请稍后再试（ERR:MaterialDetail）");
    }

    /**
     * @Description：判断资源是否存在
     * @DateTime：2020/9/4 16:18
     * @Params：
     * @Return：
     */
    public Boolean getResourceIsExit(String ResId) {
        Map<String, Object> param = new HashMap<>();
        param.put("ResId", ResId);
        Map<String, String> postParam = new HashMap<>();
        postParam.put("Content-Type", "application/json;charset=UTF-8");
        try {
            String resStr = httpService.doPost(materialCenterUrl + "/api/MaterialAPI/ResDetail", JSON.toJSONString(param), postParam);
            Map resMap = (Map) JSON.parse(resStr);
            if (null != resMap) {
                if ("200".equals(resMap.get("Code").toString())) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (Exception ex) {
            LOGGER.error("getResourceIsExit--------error", ex);
            throw GlobalException.build("请求素材中心接口失败");
        }
    }
}
